package com.h4313.ghome.ui.fragments;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.R;
import com.h4313.ghome.io.TemperatureTask;
import com.h4313.ghome.io.TemperatureTask.TemperatureCallback;
import com.h4313.ghome.io.TemperaturesTask;
import com.h4313.ghome.io.TemperaturesTask.TemperaturesCallback;
import com.h4313.ghome.model.Temperature;
import com.h4313.ghome.model.TemperatureAllDay;
import com.h4313.ghome.utils.UIUtils;

public class TemperatureFragment extends ModuleFragment implements
		TemperatureCallback, TemperaturesCallback, Refreshable {

	protected TextView temperature;
	protected ProgressBar barre, mRefreshing;
	protected WebView webView;
	protected TextView tvMaj;

	private static final String FORMAT_TEMPERATURE = "%.2f °C";

	public static TemperatureFragment newInstance(String name, int id) {

		TemperatureFragment frag = new TemperatureFragment();
		Bundle b = new Bundle();
		b.putInt(PARAM_ID, id);
		b.putString(PARAM_NAME, name);
		frag.setArguments(b);
		return frag;
	}

	public static TemperatureFragment newInstance() {
		TemperatureFragment frag = new TemperatureFragment();
//		Bundle bundle = new Bundle();
//		bundle.putString(MODULE_NAME, name);
//		frag.setArguments(bundle);
		return frag;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.fragment_temperature, container,
				false);
		temperature = (TextView) v.findViewById(R.id.tv_temperature);
		barre = (ProgressBar) v.findViewById(R.id.progressBar_temperature);
		webView = (WebView) v.findViewById(R.id.wv_chart);
		tvMaj = (TextView) v.findViewById(R.id.tv_maj);
		mRefreshing = (ProgressBar) v.findViewById(R.id.refresh);
		
//		webView.loadUrl("http://chart.apis.google.com/"
//				+ "chart?cht=lc&chs=450x150&" + "chtt=Dernieres 24h&"
//				+ "chg=0,12.5,5,5&" + "chxr=1,0,40&" + "chxt=x,y&"
//				+ "chxl=1:|0|10|20|30|40&" + "chds=0,40&" + "chd=t:5,10,20");

		
		
		// webView.loadUrl("http://chart.apis.google.com/chart?" +
		// "cht=lc&chs=450x330&chd=t:7,18,11,26,22,11,14&"+
		// "chxr=1,0,30&chds=0,30&"+
		// "chco=4d89f9&"+
		// "chxt=x,y&chxl=0:|Mon|Tue|Wed|Thu|Fri|Sat|Sun&"+
		// "chls=3,1,0&"+
		// "chm=d,4d89f9,0,0,12,0|d,4d89f9,0,1,12,0|d,4d89f9,0,2,12,0|d,4d89f9,0,3,12,0|d,4d89f9,0,4,12,0|d,4d89f9,0,5,12,0|d,4d89f9,0,6,12,0&"
		// +
		// "chg=0,6.67,5,5");

		return v;
	}

	@Override
	public void onTemperatureFound(Temperature temp) {

		Animation disparait = AnimationUtils.loadAnimation(getActivity(),
				R.anim.disparait);
		
		disparait.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				barre.setVisibility(View.GONE);
			}
		});
		barre.startAnimation(disparait);
		
		mRefreshLastOneFinished = true;
		updateProgress();
		
		if (temp == null) {
			UIUtils.showToast(this, "Impossible de charger la température",
					Toast.LENGTH_SHORT);
			return;
		}

		// TODO afficher la temperature
		Date dateInt = temp.getDate();
		Calendar dateCal = Calendar.getInstance();
		dateCal.setTime(dateInt);

		String dateString = Integer
				.toString(dateCal.get(Calendar.DAY_OF_MONTH))
				+ '/'
				+ Integer.toString(dateCal.get(Calendar.MONTH))
				+ '/'
				+ Integer.toString(dateCal.get(Calendar.YEAR));
		String heureString = Integer
				.toString(dateCal.get(Calendar.HOUR_OF_DAY))
				+ "h"
				+ dateCal.get(Calendar.MINUTE);

		tvMaj.setText("Derniere mise à jour le : " + dateString + " à "
				+ heureString);

		temperature.setText(String.format(FORMAT_TEMPERATURE,
				temp.getTemperature()));
		temperature.setVisibility(View.VISIBLE);

		Animation apparait = AnimationUtils.loadAnimation(getActivity(),
				R.anim.apparait);
		
		temperature.startAnimation(apparait);

		// if (getActivity() != null) {
		// Toast.makeText(getActivity(), temp.getTemperature(),
		// Toast.LENGTH_SHORT).show();
		// }
	}

	@Override
	public void onTemperaturesFound(TemperatureAllDay tempAllDay) {

		mRefreshLast24Finished = true;
		updateProgress();
		
		Log.d("Margot", "onTemperaturesFound");
		String coords = "";
		if (tempAllDay == null) {
			UIUtils.showToast(this,
					"Impossible de charger les 24 dernieres temperatures",
					Toast.LENGTH_SHORT);
			return;
		}
		for (int i = 0; i < tempAllDay.getTemperatures().size(); i++) {
			Double tempDouble = tempAllDay.getTemperatures().get(i);
			coords += Double.toString(tempDouble);
			if (i != tempAllDay.getTemperatures().size() - 1) {
				coords += ",";
			}
		}
		String chart = "http://chart.apis.google.com/"
				+ "chart?cht=lc&chs=300x150&chtt=Dernieres 24h&chg=0,33.33,5,5&chds=0,40&chd=t:"
				+ coords;

		webView.loadUrl(chart);
	}

	private boolean mRefreshLastOneFinished = false;
	private boolean mRefreshLast24Finished = false;
	
	@Override
	public void refresh() {

		if (getActivity() == null || isDetached()) {
			return;
		}
		
		mRefreshLast24Finished = false;
		mRefreshLastOneFinished =false;

		updateProgress();
		
		barre.setVisibility(View.VISIBLE);

		String stringLastOneUrl = GHomeApplication.SERVER_URL
				+ "/temperature/lastOne/"+getModuleId();
		String stringAllDayUrl = GHomeApplication.SERVER_URL
				+ "/temperature/last24h/"+getModuleId(); // pas sure

		Activity activity = this.getActivity();
		
		ConnectivityManager connMgr = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

		if (networkInfo != null && networkInfo.isConnected()) {

			TemperatureTask task = new TemperatureTask(this);
			task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, stringLastOneUrl);

			TemperaturesTask taskAllDay = new TemperaturesTask(this);
			taskAllDay.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, stringAllDayUrl);
			Log.d("Margot", "ok");
		} else {
			System.out.print("No Network available");
		}
	}
	
	private void updateProgress() {
		mRefreshing.setVisibility( (mRefreshLast24Finished && mRefreshLastOneFinished) ? View.INVISIBLE : View.VISIBLE );
	}

}
